/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.distschedule.slice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.distschedule.ResourceTable;
import com.example.distschedule.bean.Command;
import com.example.distschedule.bean.DeviceResult;
import com.example.distschedule.bean.RespondBase;
import com.example.distschedule.rx2.OKHttpUtilsRx2;
import com.example.distschedule.toast.XToastUtils;
import com.example.distschedule.utils.CommandUtil;
import com.example.distschedule.utils.CommonUtil;
import com.example.distschedule.utils.DeviceStateUtil;
import com.example.distschedule.utils.PreferencesUtil;
import com.socks.library.KLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.miscservices.timeutility.Time;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 保险柜控制页面
 *
 */
public class SafeAbilitySlice extends AbilitySlice {
    private String deviceId;
    private Text stateLeftText;
    private Text stateMainText;
    private Text stateSubText;
    private DirectionalLayout batteryDl;
    private Image closeAlarmImage;
    private Image logo;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_safe);

        deviceId = intent.getStringParam("deviceId");
        initComponents();
        initDeviceState();
    }

    private void initNetState() {
        TaskDispatcher globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(() -> {
            KLog.i("async task initNetState run");
            checkDeviceNet();
        });
    }

    private void initDeviceState() {
        // 从服务端获取设备信息
        OKHttpUtilsRx2.INSTANCE.getApi().getDeviceInfo(deviceId, PreferencesUtil.getUserId(getContext()))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase<DeviceResult>>() {
                    @Override
                    public void onNext(RespondBase<DeviceResult> deviceInfo) {
                        KLog.i(deviceInfo);
                        if (deviceInfo.isSuccess() && deviceInfo.getResult().isOnline()) {
                            updateData(deviceInfo.getResult().getProperty());
                        } else {
                            initNetState();
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        initNetState();
                    }
                });
    }

    private void updateData(String property){
        // 更新状态
        // 保险柜是否震动
        boolean isVibrate = "ON".equals(DeviceStateUtil.getKeyValue(property, "VibrationValue"));
        if (isVibrate) {
            setAlarmState();
        } else {
            setNormalState();
        }
    }

    private void checkDeviceNet() {
        Time.sleep(10 * 1000);
        OKHttpUtilsRx2.INSTANCE.getApi().getDeviceInfo(deviceId, PreferencesUtil.getUserId(getContext()))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase<DeviceResult>>() {
                    @Override
                    public void onNext(RespondBase<DeviceResult> deviceInfo) {
                        super.onNext(deviceInfo);
                        KLog.i(deviceInfo);
                        if (deviceInfo.getResult() == null || !deviceInfo.getResult().isOnline()) {
                            XToastUtils.toast("未配网成功，请再次碰一碰重试");
                        }
                    }
                });
    }

    private void initComponents() {
        // 设备大图标
        logo = (Image) findComponentById(ResourceTable.Id_safe_image_logo);
        // 状态文本
        stateLeftText = (Text) findComponentById(ResourceTable.Id_safe_text_state_left);
        stateMainText = (Text) findComponentById(ResourceTable.Id_safe_text_state_main);
        stateSubText = (Text) findComponentById(ResourceTable.Id_safe_text_state_sub);
        // 右侧电池/停止报警按钮
        batteryDl = (DirectionalLayout) findComponentById(ResourceTable.Id_safe_dl_battery);
        closeAlarmImage = (Image) findComponentById(ResourceTable.Id_safe_image_close);
        closeAlarmImage.setClickedListener(this::stopAlarm);
        // 用户管理 临时密码
        findComponentById(ResourceTable.Id_safe_dl_user).setClickedListener(component -> {
            XToastUtils.toast("暂不支持敬请期待，敬请期待");
        });
        findComponentById(ResourceTable.Id_safe_dl_password).setClickedListener(component -> {
            XToastUtils.toast("暂不支持敬请期待，敬请期待");
        });
        // 返回
        findComponentById(ResourceTable.Id_safe_img_left).setClickedListener(this::goBack);
        // 开箱记录
        findComponentById(ResourceTable.Id_safe_dl_report).setClickedListener(component -> {
            XToastUtils.toast("暂不支持敬请期待，敬请期待");
        });
        // 保险柜锁定
        Text lockText = (Text) findComponentById(ResourceTable.Id_safe_text_lock_state);
        Switch lockSwitch = (Switch) findComponentById(ResourceTable.Id_safe_switch_lock);
        CommonUtil.setSwitchStyle(lockSwitch);
        lockSwitch.setCheckedStateChangedListener((button, isChecked)->{
            XToastUtils.toast("暂不支持敬请期待，敬请期待");
            if (isChecked){
                lockText.setText("保险柜锁定");
            }else {
                lockText.setText("保险柜未锁定");
            }
        });
        findComponentById(ResourceTable.Id_safe_img_right).setClickedListener(component -> {
            XToastUtils.toast("智能保险柜基于3861板子OpenHarmony3.0版本，设备支持NAN配网、震动检测、状态上报和异常告警等功能");
        });
    }

    /**
     * 停止报警
     */
    private void stopAlarm(Component component){
        // 关闭告警
        sendCommand(CommandUtil.getCloseSafeAlarmCommand());
        setNormalState();
    }

    private void goBack(Component component) {
        onBackPressed();
    }

    /**
     * 设置无人状态
     */
    private void setNormalState(){
        stateLeftText.setText("安防中");
        stateLeftText.setTextColor(new Color(getColor(ResourceTable.Color_black)));
        stateMainText.setText("箱门正常");
        stateMainText.setTextColor(new Color(getColor(ResourceTable.Color_green)));
        stateSubText.setText("当前状态");
        hideStopImage();
    }

    /**
     * 设置报警状态
     */
    private void setAlarmState(){
        stateLeftText.setText("报警中");
        stateLeftText.setTextColor(new Color(getColor(ResourceTable.Color_red)));
        stateMainText.setText("00:00:10");
        stateMainText.setTextColor(new Color(getColor(ResourceTable.Color_black)));
        stateSubText.setText("保险柜被撬动");
        showStopImage();
    }

    /**
     * 显示停止按钮和异常状态图标
     */
    private void showStopImage(){
        batteryDl.setVisibility(Component.HIDE);
        closeAlarmImage.setVisibility(Component.VISIBLE);
        logo.setPixelMap(ResourceTable.Media_icon_device_alert);
    }

    /**
     * 隐藏停止按钮和显示正常图标
     */
    private void hideStopImage(){
        batteryDl.setVisibility(Component.VISIBLE);
        closeAlarmImage.setVisibility(Component.HIDE);
        logo.setPixelMap(ResourceTable.Media_img_safe);
    }

    /**
     * 发送命令
     *
     * @param command 命令
     */
    private void sendCommand(Command command) {
        JSONObject body = new JSONObject();
        body.put("commandName", command.getCommandName());
        body.put("serviceId", command.getServiceId());
        body.put("value", command.getValue());
        OKHttpUtilsRx2.INSTANCE.getApi().sendCommand(deviceId,
                RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), JSON.toJSONString(body)))
                .compose(OKHttpUtilsRx2.INSTANCE.ioMain())
                .subscribe(new OKHttpUtilsRx2.SubjectImpl<RespondBase>() {
                    @Override
                    public void onNext(RespondBase respond) {
                        super.onNext(respond);
                        if (respond.isSuccess()) {
                            XToastUtils.toast("控制命令发送成功");
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                        if ("SetDetectionStatus".equals(command.getCommandName())){
                            // 命令发送失败
                            setAlarmState();
                        }
                    }
                });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
